﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Money.Interfaces;
using Money.Data;
using One.Framework;

namespace Money.Services
{
    public class AccountTypeService : IAccountTypeService
    {

        Money.Data.MoneyManagerDataContext context = new MoneyManagerDataContext();

        public AccountTypeService()
        {
            context = new MoneyManagerDataContext();
        }

        public List<AccountType> GetAccountTypes()
        {
            return context.AccountTypes.ToList<AccountType>();
        }

        public AccountType GetAccountTypeById(int id)
        {
            return context.AccountTypes.SingleOrDefault<AccountType>(ac => ac.Id == id);
        }

        public void CreateAccountType(AccountType item)
        {
            try
            {
                context.AccountTypes.InsertOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot create account type");
            }
        }

        public void DeleteAccountType(int id)
        {
            try
            {
                AccountType item = GetAccountTypeById(id);
                context.AccountTypes.DeleteOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot delete account type");
            }
        }

        public void UpdateAccountType(AccountType item)
        {
            try
            {
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot update account type");
            }
        }

        public List<AccountType> GetAccountTypes(string orderBy, string orderDirection, int page, int pageSize, out int totalRecords)
        {
            try
            {
                var query = from ac in context.AccountTypes
                            select ac;
                return query.OrderByPaging<AccountType>(orderBy, orderDirection, page, pageSize, out totalRecords).ToList<AccountType>();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot get account types");
            }
        }

        public bool CanDelete(int id)
        {
            AccountType item = GetAccountTypeById(id);
            if (item != null)
            {
                if (item.Accounts.Count > 0)
                    return false;
            }
            return true;
        }
    }
}
